// SourceDialog.cpp : implementation file
//

#include "stdafx.h"
#include "SourceDialog.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSourceDialog dialog


CSourceDialog::CSourceDialog(CWnd* pParent /*=NULL*/)
	: CDialog(CSourceDialog::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSourceDialog)
	//}}AFX_DATA_INIT
}

void CSourceDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSourceDialog)
	DDX_Control(pDX, IDC_EDIT_SOURCE, m_RTE);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSourceDialog, CDialog)
	//{{AFX_MSG_MAP(CSourceDialog)
	ON_WM_SIZE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSourceDialog message handlers

void CSourceDialog::OnSize(UINT nType, int cx, int cy) 
{
	CDialog::OnSize(nType, cx, cy);
	
	CRect	rect;

	if(m_RTE.GetSafeHwnd())
	{
		GetClientRect(&rect);
		m_RTE.MoveWindow(&rect);
	}
}

void CSourceDialog::ShowSource(MSHTML::IHTMLDocument2Ptr ptrDoc)
{
	HGLOBAL				hMem = NULL;
	LPSTREAM			pStream = NULL;
	IPersistStreamInit	*pPersistStream = NULL;
	ULARGE_INTEGER		uli;
	HRESULT				hr;
	hr = ptrDoc.QueryInterface(IID_IPersistStreamInit, &pPersistStream);
	if(pPersistStream == NULL)
		return;
	if(FAILED(pPersistStream->GetSizeMax(&uli)))
	{
		pPersistStream->Release();
		return;
	}
	//if(uli.LowPart == 0)
	//{
		//pPersistStream->Release();
		//return;
	//}

	uli.LowPart = 65536;
	hMem = ::GlobalAlloc(GPTR, uli.LowPart);
	if(hMem == NULL)
	{
		pPersistStream->Release();
		return;
	}

	hr = ::CreateStreamOnHGlobal(hMem, TRUE, &pStream);
	if(FAILED(hr))
	{
		pPersistStream->Release();
		::GlobalFree(hMem);
		return;
	}
	hr = pPersistStream->Save(pStream, TRUE);
	
	//AfxMessageBox((LPCTSTR)hMem);
	SendMessage(WM_SIZE);
	
	m_RTE.SetWindowText((LPCTSTR)hMem);
	m_RTE.SetSel(0, 0);
	hr = pPersistStream->Release();
	pStream->Release();	
}

void CSourceDialog::PostNcDestroy() 
{
	delete this;

	CDialog::PostNcDestroy();
}
